from django.core.cache import cache
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework.decorators import action
from rest_framework.exceptions import APIException
from utils.APIResponse import APIResponse
from libs import tencent_sms_v3
from .models import User
from .serializer import MulLoginSerializer, SmsLoginSerializer, RegisterSerializer

import redis
from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from utils.redis_pool import POOL
from celery_task.user_task import create_user


class TestView(APIView):
    def get(self, requeste):
        # conn = redis.Redis(connection_pool=POOL)
        # print(conn.get('name'))

        # conn=get_redis_connection()
        # print(conn.get('name'))

        # cache.set('wife', ['dlrb', 'lyf'])  # django的缓存，放在redis中
        # print(cache.get('name'))

        res = 'hello world'
        # 记录日志
        # logger.info("我执行了一下")
        print(res)
        return Response('ok')
        # create_user.delay('18066666666', 'lzjuser', 'asd123...')
        # return Response('用户创建任务提交')


# 验证手机号是否存在的接口
class MobileView(ViewSet):
    # get 请求携带手机号 校验手机号
    @action(methods=['GET'], detail=False)
    def check_mobile(self, request):
        try:
            mobile = request.query_params.get('mobile')
            User.objects.get(mobile=mobile)
            return APIResponse()  # {code: 100, msg: successfully} 前端判断是否 100 即可
        except Exception as e:
            raise APIException(str(e))  # 处理了全局异常


# 多方式登录接口
class LoginView(GenericViewSet):
    serializer_class = MulLoginSerializer
    queryset = User

    # 多方式登录 和 验证码
    # login 不是保存 但是用 post 把验证逻辑写到序列化类中
    @action(methods=['POST'], detail=False)
    def mul_login(self, request):
        return self._common_login(request)

    @action(methods=['POST'], detail=False)
    def sms_login(self, request):
        return self._common_login(request)

    def _common_login(self, request):
        try:
            ser = self.get_serializer(data=request.data, context={'request': request})
            ser.is_valid(raise_exception=True)  # 如果校验失败 直接抛出异常 不用if判断
            token = ser.context.get('token')
            username = ser.context.get('username')
            icon = ser.context.get('icon')
            return APIResponse(data={'token': token, 'username': username, 'icon': icon})
        except Exception as e:
            raise APIException(str(e))

    def get_serializer_class(self):
        if self.action == 'mul_login':
            return self.serializer_class
        else:
            return SmsLoginSerializer


# 发送短信接口
class SendSmsView(ViewSet):
    @action(methods=["GET"], detail=False)
    def send_message(self, request):
        try:
            phone = request.query_params.get('phone')
            code = tencent_sms_v3.get_code()
            print(code)
            # 保存验证码到缓存中
            cache.set("sms_cache_%s" % phone, code, 300)
            res = tencent_sms_v3.send_sms(phone, code)
            if res:
                return APIResponse(data="短信发送成功")
        except Exception as e:
            raise APIException(str(e))


# 短信注册接口
class RegisterView(GenericViewSet, CreateModelMixin):
    serializer_class = RegisterSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return APIResponse(data="注册成功")
